// import { login, logout, getInfo } from '@/api/userOld'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import userApi from '@/api/user'
import { Routes, allAsyncRoutes, anyRoute } from '@/router/routes'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'


function filterAsyncRoutes(allAsyncRoutes, routeNames) {
  return allAsyncRoutes.filter(item => {
    if (routeNames.indexOf(item.name) !== -1) {
      if (item.children && item.children.length) {
        item.children = filterAsyncRoutes(item.children, routeNames)
      }
      return true
    }
  })
}

function addRoutes(routes) {
  // try {
    router.matcher.addRoutes(routes)
  // } catch (error) {
  //   console.log(error);
  // }

  // console.log(router);
  // routes.forEach(item => {
  //   try {
  //     console.log('addRoute', item);
  //     router.addRoute(item)
  //   } catch (error) {
  //     console.log(error);
  //   }
  // })
}

const state = {
    token: localStorage.getItem('token_key') || '',
    name: '',
    avatar: '',
    routes: Routes,
    buttons: []
  }

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES(state, routes) {
    state.routes = routes
  },
  SET_USERASYNCROUTES(state, userAsyncRoutes) {
    state.userAsyncRoutes = userAsyncRoutes
  },
  SET_BUTTONS(state, buttons) {
    state.buttons = buttons
  }
}


const actions = {
  // user login
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  
  async login({ commit }, userInfo) {
    try {
      const result = await userApi.getToken(userInfo)
      if (result.code === 20000) {
        commit('SET_TOKEN', result.data.token)
        localStorage.setItem('token_key', result.data.token)
        return 'ok'
      } else {
        return Promise.reject(new Error('获取token失败')) 
      }
    } catch (error) {
      return Promise.reject(new Error('请求获取token失败'))
    }
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user logout

  async getInfo({ commit }) {
    try {
      const result = await userApi.getUserInfo()
      if (result.code === 20000) {
        commit('SET_NAME', result.data.name)
        commit('SET_AVATAR', result.data.avatar)

        // 筛选路由 -> 注册路由 -> 更新渲染用的路由列表
        let userAsyncRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes), result.data.routes)

        addRoutes(userAsyncRoutes.concat(anyRoute))

        commit('SET_ROUTES', Routes.concat(userAsyncRoutes))

        commit('SET_BUTTONS', result.data.buttons)

        return 'ok'
      } else {
        return Promise.reject(new Error('获取userInfo失败'))
      }
    } catch (error) {
        return Promise.reject(new Error('连接服务器失败或token过期'))
    }
  },

  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  async logout({ commit, dispatch }) {
    try {
      const result = await userApi.userLogout()
      if (result.code === 20000) {
        await dispatch('reset')
        return 'ok'
      } else {
        return Promise.reject(new Error('退出登录失败'))
      }
    } catch (error) {
      return Promise.reject(new Error('请求退出登录失败'))
    }
  },

  // remove token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     removeToken() // must remove  token  first
  //     commit('RESET_STATE')
  //     resolve()
  //   })
  // }

  reset({ commit }) {
    return new Promise(resolve => {
      localStorage.removeItem('token_key')
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
      commit('SET_BUTTONS', [])
      resetRouter()
      resolve()
    })
  }
}



export default {
  namespaced: true,
  state,
  mutations,
  actions
}

